/**
 * BaseTask.java
 * 
 * Create Version: 1.0
 * Create Date: 2012-4-23
 */
package com.yinhai.asynctask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.yinhai.util.NullUtils;

/**
 * BaseTask 异步任务基类
 * 
 */
public abstract class BaseTask<Params, Progress, Result> extends
		AsyncTask<Params, Progress, Result> {
	protected String message;
	protected Boolean error = false;
	protected Context context;
	protected ProgressDialog loadMask;
	protected Boolean hasLoadMask = false;
	private boolean isDisPaly;

	public BaseTask(Context context) {
		this.context = context;
	}

	public BaseTask(Context context, String loadingMsg) {
		this.context = context;
		this.hasLoadMask = NullUtils.isNotEmpty(loadingMsg);
		this.message = loadingMsg;
	}

	public BaseTask(Context context, String loadingMsg, boolean isDisPlay) {
		this(context, loadingMsg);
		this.isDisPaly = isDisPlay;
	}

	@Override
	protected Result doInBackground(Params... params) {
		try {
			return doInBack(params);
		} catch (Exception e) {
			message = e.getMessage();
		}

		error = true;
		return null;
	}

	@Override
	protected void onPostExecute(Result result) {
		super.onPostExecute(result);

		if (this.hasLoadMask && this.loadMask != null
				&& isContextStatus(context)) {
			this.loadMask.dismiss();
		}

		if (error) {
			onError();
		} else {
			onSuccess(result);
		}
	};

	protected String getString(int resId) {
		return context.getString(resId);
	}

	protected void onError() {
		if (isContextStatus(context)) {
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
		}

	}

	protected void onPreExecute() {
		if (this.hasLoadMask && isContextStatus(context)) {
			if (context != null) {
				loadMask = new ProgressDialog(context);
			}
			if (NullUtils.isNull(this.loadMask)) {
				// this.loadMask.show();
				this.loadMask = ProgressDialog.show(this.context, null,
						this.message);
			} else {
				this.loadMask.setTitle(message);
				if (isContextStatus(context)) {
					this.loadMask.show();
				}

			}
		}
	}

	protected abstract void onSuccess(Result result);

	protected abstract Result doInBack(Params... params) throws Exception;

	private boolean isContextStatus(Context context) {
		if (context == null || (context instanceof Activity)
				&& ((Activity) context).isFinishing()) {
			return false;
		}
		return true;
	}
}
